<script setup lang="ts">
import { ref, computed, toRaw } from "vue";
import Plus from "~icons/ep/plus";
import { useMenu } from "./columns";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Delete from "~icons/ep/delete";
import EditPen from "~icons/ep/edit-pen";
import Refresh from "~icons/ep/refresh";
import AddFill from "~icons/ri/add-circle-line";
import Empty from "@/assets/common/empty.svg?component";
import "plus-pro-components/es/components/dialog-form/style/css";
import { isAllEmpty } from "@pureadmin/utils";
import { getMenuList, setMenu, addMenu } from "@/api/system";
import {
  type PlusColumn,
  type FieldValues,
  PlusDialogForm
} from "plus-pro-components";
import { underscoreToCamel } from "@/utils/common";
import { type Action, ElMessageBox, ElMessage } from "element-plus";
defineOptions({
  name: "SystemMenu"
});

const formRef = ref();
const visible = ref(false);
const edit = ref(false);
const confirmLoading = ref(false);
const values = ref<FieldValues>({});
const tableRef = ref();
const { loading, dataList, columns, loadData, formPermsColumns } = useMenu();
const rules = {
  name: [
    {
      required: true,
      message: "菜单必填"
    }
  ],
  type: [
    {
      required: true,
      message: "菜单类型必填"
    }
  ],
  routeUrl: [
    {
      required: true,
      message: "路由必填"
    }
  ],
  sort: [
    {
      required: true,
      message: "排序必填"
    }
  ]
};
const options = ref([]);
const getMenuOptions = async row => {
  try {
    const { data } = await getMenuList();
    const list = data
      .filter(item => item.p_id === 0)
      .map((item: any) => ({
        label: item.name,
        value: item.id
      }));

    options.value = [{ label: "顶级菜单", value: 0 }, ...list];
    if (edit.value) {
      values.value.pId = row.p_id;
    } else {
      if (row) {
        console.log("addd", row);
        values.value.pId = row.id;
      } else {
        values.value.pId = options.value[0].value;
      }
    }
  } catch (error) {
    console.error(error);
  }
};
const formColumns: PlusColumn[] = [
  {
    label: "菜单名称",
    prop: "name",
    valueType: "input"
  },
  {
    label: "上级菜单",
    prop: "pId",
    valueType: "select",
    options: computed(() => options.value)
  },
  {
    label: "菜单类型",
    prop: "type",
    valueType: "select",
    options: [
      {
        label: "菜单",
        value: "menu"
      },
      {
        label: "页面",
        value: "hidden"
      }
    ]
  },
  {
    label: "路由",
    prop: "routeUrl",
    valueType: "input"
  },
  {
    label: "图标",
    prop: "routeIcon",
    valueType: "input"
  },
  {
    label: "排序",
    prop: "sort",
    valueType: "input-number"
  },
  {
    label: "权限",
    prop: "power"
  }
];
const addClick = (row?: any) => {
  edit.value = false;
  values.value = { type: "menu", sort: 1, power: [] };
  visible.value = true;
  getMenuOptions(row);
};
const editClick = (row: any) => {
  edit.value = true;
  visible.value = true;
  values.value = underscoreToCamel(row);
  getMenuOptions(row);
};
const handleSubmit = async (value: FieldValues) => {
  const updatedValues = { ...values.value };
  confirmLoading.value = true;

  if (edit.value) {
    try {
      const menuId = updatedValues.id;
      delete updatedValues.id;
      updatedValues.menuId = menuId;
      await setMenu(updatedValues);
      visible.value = false;
      confirmLoading.value = false;
      formRef.value?.formInstance?.resetFields();
      loadData();
      ElMessage.success("修改成功");
    } catch (error) {
      confirmLoading.value = false;
      console.log(error, "error");
    }
  } else {
    try {
      await addMenu(updatedValues);
      visible.value = false;
      confirmLoading.value = false;
      formRef.value?.formInstance?.resetFields();
      loadData();
    } catch (error) {
      confirmLoading.value = false;
      console.log(error, "error");
    }
  }
};

function onFullscreen() {
  // 重置表格高度
  tableRef.value.setAdaptive();
}

function onAddPower() {
  if (!values.value.power) values.value.power = [];
  values.value.power.push({
    title: "",
    code: ""
  });
}
function onDelPower(row) {
  const index = values.value.power.indexOf(row);
  if (index !== -1) values.value.power.splice(index, 1);
}

function handleDelete(row) {
  ElMessage.error("暂不支持");
}
</script>

<template>
  <ElCard>
    <PureTableBar
      title="菜单管理"
      :columns="columns"
      :isExpandAll="false"
      :tableRef="tableRef?.getTableRef()"
      @refresh="loadData"
      @fullscreen="onFullscreen"
    >
      <template #buttons>
        <el-button
          type="primary"
          :icon="useRenderIcon(AddFill)"
          @click="addClick()"
        >
          新增菜单
        </el-button>
      </template>
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          ref="tableRef"
          showOverflowTooltip
          adaptive
          :adaptiveConfig="{ offsetBottom: 45 }"
          align-whole="center"
          row-key="id"
          table-layout="auto"
          :loading="loading"
          :size="size"
          :data="dataList"
          :columns="dynamicColumns"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
        >
          <template #route_icon="{ row }">
            <div class="flex flex-col items-center gap-0.5">
              {{ row.route_icon }}
              <el-icon>
                <component :is="useRenderIcon(toRaw(row.route_icon))" />
              </el-icon>
            </div>
          </template>
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              type="primary"
              :size="size"
              :icon="useRenderIcon(EditPen)"
              @click="editClick(row)"
            >
              修改
            </el-button>
            <el-button
              v-show="row.menuType !== 3"
              :disabled="row.p_id !== 0"
              class="reset-margin"
              type="success"
              :size="size"
              :icon="useRenderIcon(AddFill)"
              @click="addClick(row)"
            >
              新增
            </el-button>
            <el-popconfirm
              :title="`是否确认删除菜单名称为的这条数据${row?.children?.length > 0 ? '。注意下级菜单也会一并删除，请谨慎操作' : ''}`"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button
                  :disabled="!isAllEmpty(row.children)"
                  class="reset-margin"
                  type="danger"
                  :size="size"
                  :icon="useRenderIcon(Delete)"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </pure-table>
      </template>
    </PureTableBar>
    <PlusDialogForm
      ref="formRef"
      v-model:visible="visible"
      v-model="values"
      :form="{ columns: formColumns, rules, labelWidth: 120 }"
      :dialog="{ confirmLoading, draggable: true }"
      :title="edit ? '编辑菜单' : '添加菜单'"
      @confirm="handleSubmit"
    >
      <template #plus-field-power>
        <pure-table
          border
          row-key="key"
          align-whole="center"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
          :data="values.power"
          :columns="formPermsColumns"
        >
          <template #empty>
            <Empty fill="var(--el-svg-monochrome-grey)" class="m-auto" />
          </template>
          <template #append>
            <el-button
              type="success"
              class="w-full my-2!"
              :icon="useRenderIcon(AddFill)"
              @click="onAddPower"
            >
              添加一行数据
            </el-button>
          </template>
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              link
              type="primary"
              :icon="useRenderIcon(Delete)"
              @click="onDelPower(row)"
            />
          </template>
        </pure-table>
      </template>
    </PlusDialogForm>
  </ElCard>
</template>
